import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.NameResolver;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class LocalNameResolver extends NameResolver {
    private final Map<String, Object> config;

    public LocalNameResolver(Map<String, Object>  config) {
        this.config = config;
    }

    @Override
    public String getServiceAuthority() {
        return "none";
    }

    // 配置可用服务，RPC在调用的时候，轮询选择这里配置的可用的服务地址列表
    @Override
    public void start(Listener listener) {
        log.info("LocalNameResolver start ...");
        ArrayList<EquivalentAddressGroup> addressGroups = new ArrayList<EquivalentAddressGroup>();
        // 获取rpc地址的配置列表
        // 地址格式 host1:8080,host2:8081
        String[] hosts = config.get("hosts").toString().split(",");
        for (String host : hosts) {
            if (host.trim().length() > 0) {
                String[] address = host.split(":");
                List<SocketAddress> socketAddresses = new ArrayList<>();
                socketAddresses.add(new InetSocketAddress(address[0], Integer.parseInt(address[1])));
                addressGroups.add(new EquivalentAddressGroup(socketAddresses));
            }
        }
        listener.onAddresses(addressGroups, Attributes.EMPTY);
    }

    @Override
    public void shutdown() {

    }
}